class NetManager
	def initialize(id)
		@id=id.to_s
	end
	def is_friend(friend_id)
		if @friends_ids.nil?
		    require 'set'
			friends=Friend.find(:all,:conditions=>"user_id="+@id)
    		friends=[] if friends.nil?
			@friends_ids=Set.new
			friends.each{|n| @friends_ids<<n.friend_id}
		end
		@friends_ids.include?(friend_id)
	end
	def is_joined(friend_id)
		if @joined_ids.nil?
		    require 'set'
		  	his_connections=UserConnection.find(:all,:conditions=>["friend_id=:friend_id and thetime > :time ",{:friend_id=>@id,:time=>6.minutes.ago}])
    		his_connections=[] if his_connections.nil?
			@joined_ids=Set.new
			his_connections.each{|n| @joined_ids<<n.user_id}
		end
		@joined_ids.include?(friend_id)
	end
	def join_net(friend_id)
	  	connection=UserConnection.find(:first,:conditions=>["friend_id=:friend_id and user_id=:user_id",{:friend_id=>@id,:user_id=>friend_id}])
	  	if connection.nil?
	  		connection=UserConnection.new
	  		connection.user_id=friend_id
	  		connection.friend_id=@id
	  	end
	    connection.thetime=Time.new
		connection.save
	end
  	def leave_net(friend_id)
  		return if(@id.to_i==friend_id.to_i)
	  	connections=UserConnection.find(:all,:conditions=>["friend_id=:friend_id and user_id=:user_id",{:friend_id=>@id,:user_id=>friend_id}])
	  	unless connections.nil?
	  		connections.each{|u|u.destroy}
	  	end
  	end
	def add_friend(friend_id)
	  	friend=Friend.find(:first,:conditions=>["user_id=:user_id and friend_id=:friend_id",{:friend_id=>friend_id,:user_id=>@id}])
	  	if friend.nil?
	  		friend=Friend.new
	  		friend.user_id=@id
	  		friend.friend_id=friend_id
	  		friend.save
	  	end
  	end
  	def add_friend_with_notify(friend_id,request)
  		add_friend(friend_id)
	  	he=User.find(friend_id)
	  	if(he.notifyme==1)
			me=User.find(@id)
  			KerjoMailer.deliver_notify(me.email,he.email,me.login,he.login,(request.protocol << request.host_with_port)+"/index/accept?hashkey="+he.hashkey)
	  	end
  	end
  	def remove_friend(friend_id)
  		return if(@id.to_i==friend_id.to_i)
  	  	friends=Friend.find(:all,:conditions=>["user_id=:user_id and friend_id=:friend_id",{:friend_id=>friend_id,:user_id=>@id}])
  		unless friends.nil?
  			friends.each{|u|u.destroy}
  		end
  	end
end